package com.api.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.api.dao.UserDao;
import com.api.domain.dto.LoginDTO;
import com.api.domain.entity.UserEntity;
import com.api.domain.vo.LoginVO;
import com.api.domain.vo.UserInfoVO;
import com.api.domain.vo.UserVO;
import com.api.jwt.TokenUtil;
import com.api.utils.MD5;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Value;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author hxm
 */
@Bean
public class UserService {

    @Autowired
    private UserDao userDao;


    @Autowired
    private TokenService tokenService;

    @Value("token.exp")
    private Long exp;

    public UserInfoVO getUserInfo(Integer userId) {
        UserEntity userByUserId = userDao.findUserByUserId(userId);
        if (userByUserId == null) {
            return null;
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setAvatar(userByUserId.getAvatar());
        userInfoVO.setUserId(userByUserId.getId());
        userInfoVO.setUsername(userByUserId.getUsername());
        userInfoVO.setName(userByUserId.getNickName());
        userInfoVO.setIntroduction("铁憨憨一个");

        return userInfoVO;
    }


    public LoginVO login(LoginDTO loginDTO) {
        UserEntity userEntity = userDao.findUserByUsername(loginDTO.getUsername());
        if (userEntity == null) {
            return null;
        }
        String md5 = MD5.getMd5(loginDTO.getPassword());
        if (md5 == null) {
            return null;
        }
        if (md5.equalsIgnoreCase(userEntity.getPassword())) {
            String token = TokenUtil.token(userEntity.getId(), userEntity.getUsername(), exp);
            tokenService.addToken(token, userEntity.getId());
            return new LoginVO(token, userEntity.getUsername(), userEntity.getId(), userEntity.getNickName(), userEntity.getAvatar());
        }
        return null;
    }

    public IPage<UserVO> list(long pageNumber, long pageSize) {
        return userDao.list(pageNumber, pageSize);
    }

}
